package com.ztom.top100;

import java.util.HashMap;
import java.util.Map;

/**
 * 两数之和
 * <p>
 * https://leetcode-cn.com/problems/two-sum/
 *
 * @author ZhangTao
 */
public class Code01TwoSum {

    public int[] twoSum(int[] nums, int target) {
        if (nums == null) {
            return null;
        }
        int[] res = new int[2];
        // <补数, index>
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int another = target - nums[i];
            // 补数存在
            if (map.containsKey(another)) {
                res[0] = map.get(another);
                res[1] = i;
                return res;
            }
            map.put(nums[i], i);
        }
        return res;
    }
}
